

#!/usr/bin/env ruby

require 'yaml'
require 'fileutils'
require 'digest'
require 'base64'

# used to do package build configs for user side
class PackUploadFields
  def initialize(job)
    @job = job
  end

  def pack(upload_fields)
    packed_upload_fields = []
    #iter every item in upload_fields from server, generate upload_fields pack of content
    upload_fields.each do |upload_field|
      #puts upload_field
      if upload_field =~ /ss\..*\.config.*/
        ss = @job["ss"]
        key_arr = upload_field.split(".")
        file_path = ss[key_arr[1]][key_arr[2]]
        #puts file_path
      else
        file_path = @job[upload_field]
      end
      #if file not exist, raise error
      raise "\n #{upload_field}: #{file_path}
        This file not found in server, so we need upload it, but we not found in local.
        Please check the filepath \"#{file_path}\"  is exist in your file system."  unless File.exist?(file_path)
      packed_upload_fields << generate_upload_field_hash(upload_field, file_path)
    end
    return packed_upload_fields
  end

  def generate_upload_field_hash(field_name, file_path)
    upload_field = {}
    #set upload file MD5
    md5 = Digest::MD5.hexdigest File.read(file_path)
    upload_field["md5"] = md5
    #set field name
    upload_field["field_name"] = field_name
    #set upload file name
    file_name = File.basename(file_path)
    upload_field["file_name"] = file_name
    #set upload file content (base64)
    content = Base64.encode64(File.read(file_path)).chomp
    upload_field["content"] = content
    return upload_field
  end
end

